<template>
  <div style="width: 1520px;height: auto">
    <LandHomeHeader style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)"></LandHomeHeader>
    <div class="LandHomebox1">
      <label style="position: absolute;left: 10px;top: 25px">全部课程</label>
<!--      <el-button @click="isShow=true" v-if="currentUser.role=='teacher'"-->
<!--                 style="position: absolute;right: 10px;top: 15px">+ 新建课程-->
<!--      </el-button>-->
      <el-dropdown style="position: absolute;right: 10px;top: 15px" v-if="currentUser.role=='teacher'">
        <el-button type="primary">
          加入/新建课程
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="open">加入课程</el-dropdown-item>
          <el-dropdown-item @click.native="isShow=true">新建课程</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button @click="open" v-show="currentUser.role=='student'"
                 style="position: absolute;right: 10px;top: 15px">+ 加入课程
      </el-button>
      <a style="right: 160px" @click="archiveDialogVisible=true,archiveOrSortName='archiveBox'">归档管理</a>
      <a style="right: 260px" @click="archiveDialogVisible=true,archiveOrSortName='sortBox'">课程排序</a>
    </div>

    <!--    归档-->
    <el-dialog :visible.sync="archiveDialogVisible">
      <el-tabs v-model="archiveOrSortName" :stretch=true type="border-card">
        <el-tab-pane name="sortBox" label="课程排序">
          <div style="width: 100%;height: 400px;overflow-y: auto">
           <transition-group name="flip-list">
            <div style="text-align: left;width: 80%;height: 40px;border: whitesmoke solid 1px;line-height: 45px" v-for="course in courses" v-if="course.archiveStatus=='false'" :key="course.eid" draggable="true" class="items" @dragstart="dragstart(course)" @dragenter="dragenter(course)" @dragend="dragend(course)">
              <i class="sortBoxI"></i>
              {{course.name}}</div>
            </transition-group>
          </div>
        </el-tab-pane>
        <el-tab-pane name="archiveBox" label="归档管理">
          <div style="width: 100%;height: 400px;overflow-y: auto">
          <div class="archiveBox" v-for="course in courses" v-if="course.archiveStatus=='true'">
            <strong style="position: absolute;top: 1rem;font-size: 1.5rem;left: 1rem">{{course.name}}</strong>
            <p style="position: absolute;top: 3rem;left: 1rem">角色：{{currentUser.role =='teacher'?'教师':'学生'}}&nbsp&nbsp&nbsp&nbsp老师：{{getCreateTeacher(course,course.createTeacherId).name}} </p>
            <el-dropdown style="position: absolute;right: 1rem;top: 2rem" trigger="click" >
      <span class="el-dropdown-link" >
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="archive(course,'false')" >恢复</el-dropdown-item>
                <el-dropdown-item  @click.native="exit(course)" >退课</el-dropdown-item>

              </el-dropdown-menu>
            </el-dropdown>
          </div>

          </div>
        </el-tab-pane>
      </el-tabs>
      <!--      <el-table :data="gridData">-->
      <!--        <el-table-column property="date" label="日期" width="150"></el-table-column>-->
      <!--        <el-table-column property="name" label="姓名" width="200"></el-table-column>-->
      <!--        <el-table-column property="address" label="地址"></el-table-column>-->
      <!--      </el-table>-->
    </el-dialog>

    <div class="LandHomebox2">
      <div v-for="(course,a) in courses" v-if="course.archiveStatus!='true'" :key="a" class="course" style="text-align: left">
        <div class="coursehead">
          <span @click="turnNext(course)">{{course.name}}</span>
          <p>{{course.courseClass}}</p>
          <p class="courseheadp"><img width="16px" height="16px" style="float: left;margin-top: 3px;"
                                      src="../../assets/Qr.png"> <label
            style="float: left;font-size: 15px;margin-left: 5px;margin-left: 3px;">加课码:{{course.code}}</label></p>
        </div>
        <div style="margin-left:20px;width: 251px;height: 85px;overflow: hidden">
          <p style="font-size: 13px;color: #818181">近期作业</p>
          <div v-for="(tests,index) in course.workList" v-if="index<3">
            <a class="InspectionWork" @click="turnPageTo(tests)">{{tests.workName}}</a><br>
          </div>
        </div>
        <div style="width: 270px;height: 30px;border-top: rgb(154, 154, 154,.2)solid 1px;margin-top: 8px">
          <label style="float: left;margin-left: 15px"><el-avatar style="margin-top: 5px;float: left" size="small" :src="$store.getters.getAvatarBaseUrl+getCreateTeacher(course,course.createTeacherId).avatarPath"/>
            <a style="float: left;margin-top: 5px;margin-left: 5px">{{getCreateTeacher(course,course.createTeacherId).name}}</a></label>
          <el-dropdown class="courseFootera" placement="top" trigger="click" >
      <span class="el-dropdown-link" >
        <a  slot="reference">更多</a>
      </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="archive(course,'true')"  >归档</el-dropdown-item>
              <el-dropdown-item @click.native="exit(course)" v-if="currentUser.role=='student'">退课</el-dropdown-item>
              <el-dropdown-item @click.native="del(course)" v-if="currentUser.role=='teacher'">删除</el-dropdown-item>
              <el-dropdown-item @click.native="editCourse(course)" v-if="currentUser.role=='teacher'">编辑</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <a style="float: right;margin-right: 15px;margin-top: 5px;color: #9A9A9A;cursor: pointer">置顶</a>
        </div>
      </div>


      <div class="course" style="text-align: left">
        <div class="coursehead" style="background: url('https://www.ketangpai.com/Public/Home/img/create-course.png');">

        </div>
        <div @click="open" v-if="currentUser.role=='student'"
             style="margin-left:20px;text-align: center;margin-top: 30px;font-size: 18px;color: #9A9A9A;cursor: pointer;">

          <p style="margin-bottom: 0px">+</p>
          <p style="margin-top: 0px">加入课堂</p>

        </div>
        <div @click="isShow=true" v-if="currentUser.role=='teacher'"
             style="margin-left:20px;text-align: center;margin-top: 30px;font-size: 18px;color: #9A9A9A;cursor: pointer;">

          <p style="margin-bottom: 0px">+</p>
          <p style="margin-top: 0px">新建课堂</p>
          <el-dialog
            title="新建课堂"
            :visible.sync="isShow"
            width="30%"
            :before-close="handleClose">
            <el-form :model="createCourse" status-icon :rules="rules" ref="createCourse" label-width="100px"
                     class="demo-ruleForm">
              <el-form-item label="课程名字" prop="name">
                <el-input v-model="createCourse.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="课程班级" prop="courseClass">
                <el-input v-model="createCourse.courseClass" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('createCourse'),isShow=false">确认</el-button>
                <el-button @click="isShow=false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
  import LandHomeHeader from "../../components/LandHomeHeader";
  import App from "../../App";
  import axios from "axios";
  import http from "../../utils/http";

  export default {
    name: "LandHome",
    inject: ['reload'],
    data() {
      return {
        items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
        oldNum: 0,
        newNum: 0,

        currentUser: this.$store.getters.getUser,
        isShow: false,
        courses: [],
        archiveDialogVisible: false,
        archiveOrSortName:"archiveBox",
        createCourse: {
          name: '',
          courseClass: '',
          createTeacherId: this.$store.getters.getUser.teacherId,
        },
        rules: {
          name: [
            {required: true, message: '请输入课堂名字', trigger: 'blur'},
          ],
          courseClass: [
            {required: true, message: '请输入课堂班级', trigger: 'blur'},
          ],
          addCourseCode: [
            {required: true, message: '请输入加课码', trigger: 'blur'},
          ]
        }

      }
    },

    //页面进入执行
    created() {
      this.getCourse();
    },
    components: {
      LandHomeHeader,
    },
    methods: {
      turnPageTo(work){
        // if(this.currentUser.role=='student') {
        //   if (work.totalStudentIds.indexOf(this.currentUser.studentId) == -1) {
        //     this.$message.warning("你不能查看")
        //     return
        //   }
        // }
        this.$router.push({
          path:"/operationDetails",
          query:{
            workId:work.id
          }
        })
      },
      shuffle: function() {
        this.items = _.shuffle(this.items);
      },
      // 记录初始信息
      dragstart: function(value) {
        this.oldNum = value;
      },
      // 做最终操作
      dragend: function(value) {
        if (this.oldNum != this.newNum) {
          let oldIndex = this.courses.indexOf(this.oldNum);
          let newIndex = this.courses.indexOf(this.newNum);
          let newItems = [...this.courses];
          // 删除老的节点
          newItems.splice(oldIndex, 1);
          // 在列表中目标位置增加新的节点
          newItems.splice(newIndex, 0, this.oldNum);
          // this.items一改变，transition-group就起了作用
          this.courses = [...newItems];
        }
      },
      // 记录移动过程中信息
      dragenter: function(value) {
        this.newNum = value;
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      handleCommand(command) {
        this.$message('click on item ' + command);
      },
      getCourse() {
        console.log(this.currentUser)
        let that = this
        if (this.currentUser.role == "teacher") {
          http.get('course/getCourseByTeacher', {teacherId: this.currentUser.teacherId}).then((resp) => {

            this.courses = resp.data
            console.log(this.courses)
          })
        } else {
          http.get('course/getCourseByStudent', {studentId: this.currentUser.studentId}).then(function (resp) {
            that.courses = resp.data
          })
        }
      },
      getCreateTeacher(course, createTeacherId) {
        for (let i = 0; i < course.teacherList.length; i++) {
          if (course.teacherList[i].teacherId == createTeacherId) {
            return course.teacherList[i]
          }
        }
      },
      del(course) {
        this.$confirm('你确定删除课程吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 正常跳转
          const _this = this;
          http.get('teacher/deleteCourse', {code: course.code})
            .then((res) => {
              if (res.data.code == 200) {
                this.$message.success(res.data.message);
                this.courses.splice(this.courses.indexOf(course), 1);
              } else {
                this.$message.success(res.data.message);
              }
            })
        }).catch(() => {
          // 如果取消跳转地址栏会变化，这时保持地址栏不变

        })

      },
      editCourse(course){

      },
      archive(course,archiveStatus){
        let arch={
          code:course.code,
          archiveStatus:archiveStatus
        }
        if(this.currentUser.role=="teacher"){
          arch.teacherId=this.currentUser.teacherId;
        }else if(this.currentUser.role='student'){
          arch.studentId=this.currentUser.studentId;
        }
        let title='';
        if(archiveStatus=='false'){
          title='你确定恢复课程吗？'
        }else {
          title='你确定归档课程吗？'
        }
        this.$confirm(title, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 正常跳转
          http.get('/course//archiveCourse',arch).then((res)=>{
            if (res.data.code == 200) {
              this.$message.success(res.data.message);
              this.courses[this.courses.indexOf(course)].archiveStatus=archiveStatus
            } else {
              this.$message.error(res.data.message);
            }
          })
        }).catch(() => {
          // 如果取消跳转地址栏会变化，这时保持地址栏不变

        })
      },
      exit(course) {
        this.$confirm('你确定退出课程吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 正常跳转
          http.get('student/exitCourse',
            {
              courseCode: course.code,
              studentId: this.currentUser.studentId
            }
          )
            .then((res) => {
              if (res.data.code == 200) {
                this.$message.success(res.data.message);
                this.getCourse();
              } else {
                this.$message.error(res.data.message);
              }
            })
        }).catch(() => {
          // 如果取消跳转地址栏会变化，这时保持地址栏不变

        })

      },


      submitForm(formName) {
        const _this = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // console.log(124)
            // console.log(this.createCourse)
            http.post('course/createCourse', this.createCourse)
              .then((response) => {
                if (response.data.code == 200) {
                  _this.$message.success(response.data.message)
                  _this.getCourse();
                  _this.isShow = false;
                } else {
                  this.$message.error(response.data.message)
                }
              })
              .catch(function (error) {
                console.log(error);
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      turnNext(course) {
        this.$router.push({
            path: "/Course",
          },
          this.$store.commit('setCourse', course)
        )
      },

      open() {
        const _this = this;
        let addCourse;
        this.$prompt('输入加课码', '加课', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[A-Za-z0-9]+$/,
          inputErrorMessage: '格式不正确'
        }).then(({value}) => {
          let url=""
          let params ={};
          if (this.currentUser.role == "student") {
            url='/student/joinCourse'
            params= {courseCode: value, studentId: this.currentUser.studentId}
          }else if(this.currentUser.role=="teacher") {
            url="/teacher/joinCourse"
            params={code:value,teacherId:this.currentUser.teacherId}
          }
          http.get(url, params ).then((resp) => {
            if (resp.data.code == 200) {
              this.$message({
                type: 'success',
                message: resp.data.message,
              },);
            } else if (resp.data.code == 400) {
              this.$message({
                type: "error",
                message: resp.data.message,
              })
            } else {
              this.$message({
                type: "warning",
                message: resp.data.message,
              })
            }
            _this.getCourse();
          })
        }).catch((re) => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },
    }
  }
</script>

<style scoped>
  .LandHomebox1 {
    width: 1400px;
    border-bottom: 1px solid rgba(226, 230, 237, 1);
    height: 60px;
    position: relative;
  }

  .LandHomebox1 .el-button {
    background-color: #569fe0;
    color: white;
  }

  .LandHomebox1 a {
    position: absolute;
    top: 23px;
    color: #9A9A9A;
    cursor: pointer;
  }

  .LandHomebox1 a:hover {
    color: black;
  }

  .LandHomebox1 .el-button:hover {
    background-color: #569fe0;
    color: white;
  }

  .LandHomebox2 {
    width: 1212px;
    height: 323px;
    margin-top: 25px;
  }

  .course {
    width: 271px;
    height: 290px;
    float: left;
    position: relative;
    border: rgba(226, 230, 237, 1) solid 1px;
    margin-right: 30px;
    margin-top: 30px;
    border-radius: 10px;
  }

  .coursehead {
    width: 250px;
    height: 127px;
    padding-top: 20px;
    padding-bottom: 15px;
    background: url("http://assets.ketangpai.com/theme/student/min/01.png");
    padding-left: 20px;
    color: white;
  }

  .coursehead a {
    color: white;
    text-decoration: none;
    font-size: 20px;
  }

  .coursehead a:hover {
    border-bottom: rgba(226, 230, 237, 1) solid 1px;
  }

  .courseheadp {
    height: 22px;
    background: rgba(255, 255, 255, .2);
    border-radius: 2px;
    font-size: 12px;
    font-family: PingFang-SC-Medium;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
    line-height: 22px;
    text-align: center;
    padding-right: 4px;
    margin-top: 13px;
    display: inline-block;
  }

  .courseFootera {
    background: url('https://www.ketangpai.com/Public/Home/img/more-vertical.png') no-repeat right;
    padding-right: 10px;
    background-size: 10px;
    margin-top: 5px;
    color: #32BAF0;
    float: right;
    cursor: pointer
  }

  .InspectionWork {
    font-size: 14px;
    text-decoration: none;
    color: black;
    cursor: pointer;
  }

  .InspectionWork:hover {
    color: #1da3c5;
    text-decoration: underline;
  }
</style>
<style>
  .createClass {
    position: absolute;
    padding-top: 30px;
    top: 200px;
    left: 40%;
    width: 400px;
    height: 400px;
    border: #32BAF0 solid 2px;
  }

  .createClass .el-input__inner {
    width: 200px;
  }

  .hide {
    display: none;
  }

  .createClass .el-form-item__error {
    position: relative;
  }

  .createClass .el-input__suffix {
    right: 26px;
    position: relative;
  }
  .archiveBox{
    width: 40%;
    height: 6rem;
    float: left;
    margin-left: 8%;
    margin-top: 1rem;
    position: relative;
    color: white;
    background: url('https://assets.ketangpai.com/theme/min_ar/01.jpg') no-repeat;
    background-size: 100%;
  }
  .archiveBox .el-icon--right{
    color: white;
  }
  .sortBoxI{
    display: inline-block;
    width: 19px;
    height: 19px;
    border-radius: 20px;
    background-color: #32BAF0;
    /*background-image: url('https://v4.ketangpai.com/Public/Home/img/ybg.png');*/
    /*background-repeat: no-repeat;*/
    /*vertical-align: middle;*/
    margin-right: 20px;
  }
</style>
